package listbyorder.access001_100.test54;

import java.util.ArrayList;
import java.util.List;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/6/1 16:35
 */
public class Solution1 {

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
        if (matrix == null || matrix.length == 0) return res;
        int row = matrix.length;
        int col = matrix[0].length;
        getAns(res, matrix, 0, 0, row - 1, col - 1);
        return res;
    }

    private void getAns(List<Integer> res, int[][] matrix, int sr, int sc, int er, int ec) {
        // 条件之外的就可以不用执行了
        if (sr <= er && sc <= ec) {
            if (sr == er) {
                for (int i = sc; i <= ec; i++) {
                    res.add(matrix[sr][i]);
                }
            } else if (sc == ec) {
                for (int i = sr; i <= er; i++) {
                    res.add(matrix[i][sc]);
                }
            } else {
                for (int i = sc; i < ec; i++) {
                    res.add(matrix[sr][i]);
                }
                for (int i = sr; i < er; i++) {
                    res.add(matrix[i][ec]);
                }
                for (int i = ec; i > sc; i--) {
                    res.add(matrix[er][i]);
                }
                for (int i = er; i > sr; i--) {
                    res.add(matrix[i][sc]);
                }
            }
            getAns(res, matrix, sr + 1, sc + 1, er - 1, ec - 1);
        }
    }
}
